/*
 * solution.c
 *
 *  Created on: Apr 19, 2009
 *      Author: thaison
 */

#include "mpi.h"
#include "solution.h"

MPI_Datatype MPI_Solution; // global declaration
MPI_Op MPI_SolutionMin;

void solution_min(void *_s1, void *_s2, int *N, MPI_Datatype *dt) {
	Solution *s1 = (Solution *) _s1;
	Solution *s2 = (Solution *) _s2;
	int i;
	if (*dt != MPI_Solution) {
		printf("Invalid datatype\n");
		MPI_Abort(MPI_COMM_WORLD, 3);
	}
	for (i = 0; i < *N; i++) {
		s2[i] = (s1[i].cost < s2[i].cost ? s1[i] : s2[i]);
	}
	return;
}
void construct_datatypes(void) {
	Solution p;
	int blens[3];
	MPI_Aint displ[3];
	MPI_Datatype types[3];

	blens[0] = MAX_TOWNS;
	types[0] = MPI_LONG_INT;
	displ[0] = (MPI_Aint) & p.tour - (MPI_Aint) & p;

	blens[1] = 1;
	types[1] = MPI_FLOAT;
	displ[1] = (MPI_Aint) & p.cost - (MPI_Aint) & p;

	// It is good practice to include this in case
	// the compiler pads your data structure
	blens[2] = 1;
	types[2] = MPI_UB;
	displ[2] = sizeof(Solution);

	MPI_Type_struct(3, blens, displ, types, &MPI_Solution);
	MPI_Type_commit(&MPI_Solution); // important!!

	MPI_Op_create(solution_min, 1, &MPI_SolutionMin);

	return;
}
